package bma.common.langutil.ai.objectpool;

public class ObjectTimestampPair<TYPE> implements Comparable<TYPE> {

	private TYPE value;

	private long tstamp;

	public ObjectTimestampPair(TYPE val) {
		this(val, System.currentTimeMillis());
	}

	public ObjectTimestampPair(TYPE val, long time) {
		value = val;
		tstamp = time;
	}

	/**
	 * Returns a string representation.
	 * 
	 * @return String representing this ObjectTimestampPair
	 */
	@Override
	public String toString() {
		return value + ";" + tstamp;
	}

	/**
	 * Compares this to another object by casting the argument to an
	 * ObjectTimestampPair.
	 * 
	 * @param obj
	 *            object to cmpare
	 * @return result of comparison
	 */
	@SuppressWarnings("unchecked")
	public int compareTo(Object obj) {
		return compareTo((ObjectTimestampPair<TYPE>) obj);
	}

	/**
	 * Compares this to another ObjectTimestampPair, using the timestamp as
	 * basis for comparison. Implementation is consistent with equals.
	 * 
	 * @param other
	 *            object to compare
	 * @return result of comparison
	 */
	public int compareTo(ObjectTimestampPair<TYPE> other) {
		final long tstampdiff = this.tstamp - other.tstamp;
		if (tstampdiff == 0) {
			// make sure the natural ordering is consistent with equals
			// see java.lang.Comparable Javadocs
			return System.identityHashCode(this)
					- System.identityHashCode(other);
		} else {
			// handle int overflow
			return (int) Math.min(Math.max(tstampdiff, Integer.MIN_VALUE),
					Integer.MAX_VALUE);
		}
	}

	/**
	 * @return the value
	 */
	public TYPE getValue() {
		return value;
	}

	/**
	 * @return the tstamp
	 */
	public long getTstamp() {
		return tstamp;
	}
}
